﻿using MediatR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuartzServices.Domain.CommandHandlers.BOM.Commands;
using QuartzServices.Domain.Common.HttpServices;
using QuartzServices.Domain.Core.Bus;
using QuartzServices.Domain.DomainModels;
using QuartzServices.Domain.Interfaces;
using QuartzServices.Infrastructure.Common.Attributes;
using QuartzServices.Infrastructure.Common.Constant;
using QuartzServices.Infrastructure.Common.Extensions;

namespace QuartzServices.Domain.CommandHandlers.BOM
{
    public class BlcSapLocationSyncHandler : CommandHandler,
        IRequestHandler<BlcSapLocationSyncCommand, bool>
    {
        private readonly ILogger<BlcSapLocationSyncHandler> _logger;
        private readonly IMediatorHandler _mediator;
        private readonly BlcSapLocationClient _blcSapLocationClient;
        private readonly IRepository<BlcSapLocationModel> _repository;

        public BlcSapLocationSyncHandler(
            IUnitOfWork uow,
            IMediatorHandler bus,
            BlcSapLocationClient blcSapLocationClient,
            IRepository<BlcSapLocationModel> repository,
            ILogger<BlcSapLocationSyncHandler> logger) : base(uow, bus)
        {
            _mediator = bus;
            _blcSapLocationClient = blcSapLocationClient;
            _repository = repository;
            _logger = logger;
        }

        /// <summary>
        /// 领域处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [JobName(JobNameConstant.BlcSapLocation)]
        public async Task<bool> Handle(BlcSapLocationSyncCommand request, CancellationToken cancellationToken)
        {
            try
            {

                _logger.LogAppError("日志测试123123123123123");
                var postData = new Dictionary<string, int>()
                {
                    { "CurrentPage",1},
                    { "PageRows",200}
                };

                var response = await _blcSapLocationClient.GetDataAsync(JsonConvert.SerializeObject(postData));

                var data = JObject.Parse(response["data"].ToString());
                var page = JObject.Parse(data["Page"].ToString());
                var totalPages = Convert.ToInt32(page["TotalPages"]);
                var dataList = JsonConvert.DeserializeObject<List<ResponseData>>(data["Data"].ToString());

                if (totalPages > 1)
                {
                    while (totalPages > postData["CurrentPage"])
                    {
                        try
                        {
                            postData["CurrentPage"]++;
                            response = await _blcSapLocationClient.GetDataAsync(JsonConvert.SerializeObject(postData));
                            data = JObject.Parse(response["data"].ToString());
                            var tempData = JsonConvert.DeserializeObject<List<ResponseData>>(data["Data"].ToString());
                            dataList.AddRange(tempData);
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }

                var list = dataList.Select(d => new BlcSapLocationModel
                {
                    CheckCode = DateTime.Now.ToString("yyMMdd"),
                    Plnt = d.Plnt,
                    Workcell = d.Workcell,
                    Sloc = d.Sloc,
                    Material = d.PartNumber,
                    Type = d.TYPE,
                    StandPrice = d.StdPrice,
                    Unrestricted = d.Unrestricted,
                    UnrestrCnsgt = d.Unrestr_cnsgt,
                    StockInTfr = d.Stock_in_tfr,
                    InQualInsp = d.In_qual_insp,
                    CnsgtQualIn = d.Cnsgt_qual_insp,
                    Blocked = d.Blocked,
                    TotalValue = d.Total,
                    Mrp = d.MRP,
                    UploadTime = d.UploadTime,
                    Enabled = 1,
                    Deletemark = 0,
                    Id = Guid.NewGuid().ToString(),
                    Createon = DateTime.Now,
                    Createuserid = "26F43BC9-AE6D-42D2-BAC9-F4237A949484",
                    Createby = "超级管理员"

                }).ToList();

                await _repository.AddRangeAsync(list);

                await Commit();

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }

    /// <summary>
    /// 接口返回数据模板
    /// </summary>
    public class ResponseData
    {
        public string Plnt { get; set; }
        public string Workcell { get; set; }
        public string Sloc { get; set; }
        public string PartNumber { get; set; }
        public string TYPE { get; set; }
        public decimal StdPrice { get; set; }
        public string Unrestricted { get; set; }
        public string Unrestr_cnsgt { get; set; }
        public string Stock_in_tfr { get; set; }
        public string In_qual_insp { get; set; }
        public string Cnsgt_qual_insp { get; set; }
        public string Blocked { get; set; }
        public decimal Total { get; set; }
        public string MRP { get; set; }
        public DateTime UploadTime { get; set; }
    }


}
